package com.sunriz.javafx.server.driver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * ClassName: RttClient
 * Package: com.sunriz.javafx.Server.Driver
 * Description:
 *
 * @Author BuTang
 * @Create 2024/12/5 16:48
 * @Version 1.0
 */
public class RttClient {

    private final static Logger log = LoggerFactory.getLogger(OpenocdManager.class);


    /**
     * 实现单例模式
     */
    private static volatile RttClient instance;
    private RttClient() {
    }
    public static RttClient getInstance() {
        if (instance == null) {
            synchronized (RttClient.class) {
                // 双重检查锁定，确保线程安全
                if (instance == null) {
                    instance = new RttClient();
                }
            }
        }
        return instance;
    }

        private Socket socket = null;
        private ExecutorService executorService;


    public void start() {
        // 创建一个固定大小的线程池，可以根据需求调整线程池的大小
        executorService = Executors.newFixedThreadPool(2); // 假设最大线程数为2
        executorService.submit(() -> {
            String serverAddress = "localhost";
            int port = 8888; // RTT 服务器监听的端口
            try {
                socket = new Socket(serverAddress, port);
                log.info("连接 RTT 服务器成功！");

                // 获取输入输出流
                InputStream inStream = socket.getInputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(inStream));

                // 持续读取 RTT 返回的数据
                // 缓冲区
                char[] buffer = new char[1024];

                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    String response = new String(buffer, 0, bytesRead);
                    analyzeData(response);
                }
            } catch (IOException e) {
//                e.printStackTrace();
                log.info("报错");
            }
        });
    }


        public void close() {
            if (socket != null && !socket.isClosed()) {
                try {
                    socket.close();
                    log.info("Socket 已关闭。");
                } catch (IOException e) {
                    log.error("关闭 Socket 时出错: {}" , e.getMessage());
                }
            } else {
                log.info("Socket 未打开或已关闭。");
            }

            // 关闭线程池
            if (executorService != null && !executorService.isShutdown()) {
                executorService.shutdown();
                log.info("线程池已关闭。");
            }
        }

    private static void analyzeData(String data){
        String[] split = data.split(",");
        log.info(Arrays.toString(split));
    }


}
